#!/usr/bin/env python
# encoding: utf-8
import sys
import os

reload(sys)

import time
import commands

sys.setdefaultencoding('utf8')

# 上线日志内容

# 格式化时间
def formatDate():
    current_time = time.time()
    current_time = time.localtime(current_time)
    current_time = time.strftime('%Y-%m-%d', current_time)
    return current_time


# 上线信息的push
def printPushInformantion():
    tagInformation = raw_input("请输入上线内容:")
    while not tagInformation:
        tagInformation = raw_input("请输入上线内容:")

    return tagInformation


#  检查文件中的tag
# 将上线内容写入Reademd文件
def writeOnlineContentToReadme(times, flag):
    current_time = formatDate()
    print current_time
    if flag == "1":
        current_time = 'base-' + current_time
    elif flag == "2":
        current_time = 'weixin-' + current_time
    file_tag_times = 0

    f_r = open("Reame.md", "r")
    line = f_r.readline()
    while line:
        file_tag_times = file_tag_times + line.count(current_time)
        line = f_r.readline()

    f_r.close()
    print "----a-df-a-df-af-"
    print file_tag_times
    print "------adfadf-af----"

    tagInformation = printPushInformantion()

    if times > 0:
        current_time = current_time + "-0" + times.__str__() if times / 10 == 0  else current_time + "-" + times.__str__()
    elif file_tag_times > 0 and times == 0:
        current_time = current_time + "-0" + file_tag_times.__str__() if file_tag_times / 10 == 0 else current_time + "-" + file_tag_times.__str__()
    commit_content = "`" + current_time + "` " + tagInformation

    print commit_content

    print(flag);

    if flag == "1":
        file = Insert_line("Reame.md", "--base--", commit_content)
        file.inserted_new_file()
    elif flag == "2":
        file = Insert_line("Reame.md", "--weixin--", commit_content)
        file.inserted_new_file()
    print "上线内容写入文件"
    return {"tag": current_time, "tag_content": tagInformation}  # writeOnlineContentToReadme()


# 获取远程的tag flag 为1 表示标准化，flag 为2 表示微信
def fechTag(flag):
    (status, output) = commands.getstatusoutput('git fetch')
    print output
    if status == 0:
        times = 0
        # 如果有输出，看是否有对应日期
        if output.__len__() > 0:
            current_time = formatDate()
            if flag == "1":
                times = parseString("base-" + current_time, output)
                online_log = writeOnlineContentToReadme(times, flag)
            elif flag == "2":
                times = parseString("weixin-" + current_time, output)
                online_log = writeOnlineContentToReadme(times, flag)
        else:
            online_log = writeOnlineContentToReadme(times, flag)

        return online_log


# 分析当前时间
# current_time 指tag的时间格式
# content指 string
def parseString(current_time, content):
    times = content.count(current_time)
    return times


# 提交代码

def pushCodeAndTag(tagDic):
    tag = tagDic['tag']
    tag_content = tagDic['tag_content']
    git_add = "git add ."
    git_commit = "git commit -m" + "\"" + tag_content + "\""
    git_push = "git push origin master"
    git_tag = "git tag -a " + tag + " -m" + "\"" + tag_content + "\""
    git_push_tag = "git push origin " + tag
    commandss = git_add + "&&" + git_commit + "&&" + git_push + "&&" + git_tag + "&&" + git_push_tag
    (status, output) = commands.getstatusoutput(commandss)
    if status == 0:
        print "----打tag成功-----"
    print output


def startTag(flag):
    tagDic = fechTag(flag)
    pushCodeAndTag(tagDic)


# 选择命令
def chooseApp():
    print("--选择版本---")
    print("1:标准化")
    print("2:微信版本")
    number = raw_input("请输入您的选择：")
    while not ["1", "2"].count(number):
        number = raw_input("请输入您的选择：")
    return number


def chooseCommnd(number):
    # 打包上线
    if number == "1":
        print("打包标准化")
    elif number == "2":
        print("打包微信版本")
    pack(number)


def pack(number):
    if number == "1":
        # commandss = 'gulp --key app'
        # (status, output) = commands.getstatusoutput(commandss)
        # if status == 0:
        print "打包标准化渠道成功"
        startTag(number)
        # else:
        #     print("微信渠道打包失败，请检查")

    elif number == "2":
        # commandss = 'gulp --key weixin-app'
        # (status, output) = commands.getstatusoutput(commandss)
        # if status == 0:
        print("打包微信渠道成功")
        startTag(number)
        # else:
        #     print("微信渠道打包失败，请检查")


class Insert_line(object):
    def __init__(self, file, keyword, newline):
        self.__file = file
        self.__key = keyword
        self.__newline = newline

    def _get_specify_lineno(self):
        i = 1
        try:
            f = open("%s" % self.__file)
        except IOError, e:
            print e[1] + ' "%s"' % e.filename
            sys.exit(1)
        while True:
            line = f.readline()
            if not line: break
            if "%s" % self.__key in line:
                return i
                break
            i += 1
        f.close()

    def _inserted_newline_list(self):
        if self._get_specify_lineno():
            ls = os.linesep
            f = open("%s" % self.__file)
            li = f.readlines()
            f.close()
            li.insert(self._get_specify_lineno() - 1, self.__newline + ls)
            return li

    def inserted_new_file(self):
        if self._inserted_newline_list():
            lines = self._inserted_newline_list()
            os.system("cp %s %s.bak" % (self.__file, self.__file))
            f = open("%s" % self.__file, 'w')
            f.writelines(lines)
            f.close()
            commands.getstatusoutput("rm -r Reame.md.bak")
        else:
            print 'No such keyword "%s"' % self.__key


def _main():
    file = Insert_line("Reame.md", "--weixin--", "the second line")
    file.inserted_new_file()


def start():
    chooseCommnd(chooseApp())


start()
